//---------------------------------------------------------------------
// File: SendPortConductorStep.cs
// 
// Summary: 
//---------------------------------------------------------------------
using System;
using System.Management;
using System.Xml;
using Microsoft.Services.BizTalkApplicationFramework.BizUnit;
namespace BizUnit.Extensions.BizTalk
{
	/// <summary>
	/// The SendPortConductorStep starts/stops a send port.
	/// </summary>

	/// <remarks>
	/// The following shows an example of the Xml representation of this test step.
	/// 
	/// <code escaped="true">
    /// <TestStep assemblyPath="BizUnitExtensions.BizTalk." typeName="BizUnit.Extensions.BizTalk.SendPortConductorStep">
	///		<DelayForCompletion>5</DelayForCompletion> <!-- Optional, seconds to delay for this step to complete -->
    ///		<SendPortName></SendPortName>
	///		<Action>Enable</Action>
	/// </TestStep>
	/// </code>
	///	
	///	<list type="table">
	///		<listheader>
	///			<term>Tag</term>
	///			<description>Description</description>
	///		</listheader>
	///		<item>
	///			<term>DelayForCompletion</term>
	///			<description>The number of seconds to deplay for this step to complete</description>
	///		</item>
	///		<item>
	///			<term>SendPortName</term>
	///			<description>The name of the receive port to containing the receive location to enable/dissable</description>
	///		</item>
	///		<item>
	///			<term>Action</term>
	///			<description>Start|Stop</description>
	///		</item>
	///	</list>
	///	</remarks>

	public class SendPortConductorStep : ITestStep
	{
		public enum SendPortAction 
		{
			Start,
			Stop,
		}

		#region ITestStep Members

		/// <summary>
		/// ITestStep.Execute() implementation
		/// </summary>
		/// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param>
		/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
		public void Execute(XmlNode testConfig, Context context)
		{
			string sendPortName = context.ReadConfigAsString(testConfig, "SendPortName");

			SendPortAction action = (SendPortAction)Enum.Parse( typeof(SendPortAction), context.ReadConfigAsString(testConfig, "Action"), true );

			if ( action == SendPortAction.Start )
			{
                Start(sendPortName, context);
			}
			else
			{
                Stop(sendPortName, context);
			}

			// Delay if necessary to allow the orchestration to start/stop
			int delayForCompletion = context.ReadConfigAsInt32(testConfig, "DelayForCompletion", true);
			if (delayForCompletion > 0)
			{
				context.LogInfo("Waiting for {0} seconds before recommencing testing.", delayForCompletion);
				System.Threading.Thread.Sleep(delayForCompletion*1000);
			}
		}

		#endregion

		private void Start( string sendPortName, Context context )
		{
            PerformSendPortAction(context, sendPortName, "Start");																												
		}

		private void Stop( string sendPortName, Context context )
		{
		    PerformSendPortAction(context, sendPortName, "Stop");
		}

	    private static void PerformSendPortAction(Context context, string sendPortName, string action)
	    {
	        string WMIQuery = String.Format(	"Select * from MSBTS_SendPort where Name=\"{0}\"",
	                                        	sendPortName);

	        EnumerationOptions enumOptions = new EnumerationOptions();
	        enumOptions.ReturnImmediately = false;

	        ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\MicrosoftBizTalkServer",	WMIQuery, enumOptions);							

	        foreach( ManagementObject instance in searcher.Get())
	        {
	            context.LogInfo("{0}ing Send Port {1} ", action, sendPortName );
	            instance.InvokeMethod(action, new object[] {2,2});
	        }
	    }

	    
	}
}
